package com.seven.tools.json;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import cn.hutool.json.serialize.JSONDeserializer;

import java.lang.reflect.Field;
import java.util.ArrayList;

public class BaseJsonDeserializer<T> implements JSONDeserializer<T> {

    public static <T> T jsonDeserializer(JSON json, Class<T> t) {
        BaseJsonDeserializer<T> tBaseJsonDeserializer = new BaseJsonDeserializer<>(t);
        return tBaseJsonDeserializer.deserialize(json);
    }
    private Class<T> tClass;

    public BaseJsonDeserializer(Class<T> tClass) {
        this.tClass = tClass;
    }

    @Override
    public T deserialize(JSON json) {
        try {
            ArrayList<Field> fields = new ArrayList<>();
            for (Field declaredField : tClass.getDeclaredFields()) {
                Class<?>[] interfaces = declaredField.getType().getInterfaces();
                for (Class<?> anInterface : interfaces) {
                    if (anInterface == BaseJsonEnum.class) {
                        fields.add(declaredField);
                        break;
                    }
                }
            }
            var ref = new Object() {
                String jsonStr = json.toString();
            };
            fields.forEach(s -> {
                Object byPath = json.getByPath(s.getName());
                if (byPath != null) {
                    ref.jsonStr = ref.jsonStr.replace(byPath.toString(), JSONUtil.parseObj(byPath.toString()).getStr("code"));
                }
            });
            return JSONUtil.toBean(ref.jsonStr, tClass);
        } catch (Exception e) {
            e.printStackTrace();
            return json.toBean(tClass);
        }
    }

}